package com.hdx;

import org.apache.log4j.Logger;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;

/**
 * @Auther: hdx
 * @Date: 2019/1/28 17:36
 * @Description:
 */
public class TestZookeeper {
    private static Logger logger = Logger.getLogger(TestZookeeper.class);
    private static String connectString = "10.0.0.114:2181,10.0.0.115:2181,10.0.0.116:2181";
    private static int sessionTimeout = 2000;//毫秒
    private static ZooKeeper zooKeeper;

    //1、zk中的CRUD
    //2、事件通知
    public static void main(String[] args) throws IOException, InterruptedException {
        //多长时间链接不上zk了就会session会话超时
        /**
         * 建立和zookeeper集群的连接，操作都是用它
         */
        zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            //这个是wathcher的回调方法：跟ajax的回调是一个意思，连上后会回调到这个方法里
            public void process(WatchedEvent watchedEvent) {
                System.out.println("事件回调：" + watchedEvent.getState());
            }
        });
        //new 完之后是不能立即使用zookeeper对象，需要等待远程连接正真完成，所以sleep了5,秒。等上面这个回调结束才能用这个zookeeper对象
        Thread.sleep(5000);
    }

}
